<template>
	<div class="container">
		<h2 style="text-align: center;font-weight: bold;">{{ id ? '修改' : '创建' }}发料出库</h2>
		<a-form ref="formRef" :model="formState" layout="vertical" @finish="saveUselog">
			<a-row :gutter="20">
				<a-col :span="12">
					<a-form-item label="选择项目" name="project_id" :rules="{ required: true, message: '请选择项目' }">
						<a-select v-model:value="formState.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" @change="changeProject"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<!--					<a-form-item label="选择工号" name="gonghao_id" :rules="{ required: true, message: '请选择工号' }" extra="请勿随意更改工号，更改工号后，物资的使用部位将会清除。">-->
					<!--						<a-select v-model:value="formState.gonghao_id" placeholder="请选择工号" :options="gonghaolist" option-filter-prop="label" @change="(e) => changeProjectNo(e, 1)"></a-select>-->
					<!--					</a-form-item>-->
					<a-form-item label="工号" name="gonghao_id" :rules="{ required: true, message: '请选择工号' }">
						<a-row :gutter="10">
							<a-col :span="24">
								<a-tree-select v-model:value="formState.gonghao_id" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择工号" allow-clear tree-default-expand-all :tree-data="gonghaoTree" tree-node-filter-prop="label" style="width:100%" extra="请勿随意更改工号，更改工号后，物资的使用部位将会清除。">
									<template #title="{ label }">{{ label }}</template>
								</a-tree-select>
							</a-col>
						</a-row>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="人员类型" name="opr_type" :rules="{ required: true, message: '请选择人员类型' }">
						<a-select v-model:value="formState.opr_type" placeholder="请选择人员类型" @change="changeOprType">
							<a-select-option :value="1">分包单位</a-select-option>
							<a-select-option :value="2">项目本部</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col v-show="formState.opr_type === 1" :span="12">
					<a-form-item label="分包单位" name="receiver_id" :rules="{ required: true, message: '请选择分包单位' }">
						<a-cascader v-model:value="formState.supplier" :show-search="{ filter: supplierFilter }" :disabled="!!formState.receiver2" :rules="{ required: true, message: '请选择分包单位' }" :options="supplierList" placeholder="请选择分包单位" change-on-select @change="changeSupplier" />
					</a-form-item>
				</a-col>
				<a-col v-show="formState.opr_type === 2" :span="12">
					<a-form-item label="项目本部" name="receiver_id" :rules="{ required: true, message: '请选择项目本部人员' }">
						<a-select v-model:value="formState.receiver_id" :show-search="true" placeholder="请选择" :options="projectUserList" option-filter-prop="label" :allow-clear="true"></a-select>
					</a-form-item>
				</a-col>
				<!--				<a-col :span="12">-->
				<!--					<a-form-item label="分包单位" name="supplier" :rules="{ required: !!formState.receiver2 ? false : true, message: '请选择分包单位' }" extra="分包单位授权委托人和项目本部负责人必须二选一。如需选择项目本部负责人，必须先清空分包单位授权委托人！">-->
				<!--						<a-cascader v-model:value="formState.supplier" :show-search="{ filter: supplierFilter }" :disabled="!!formState.receiver2" :rules="{ required: true, message: '请选择分包单位' }" :options="supplierList" placeholder="请选择分包单位" change-on-select @change="changeSupplier" />-->
				<!--					</a-form-item>-->
				<!--				</a-col>-->
				<!--				<a-col :span="12">-->
				<!--					<a-form-item label="项目本部" name="receiver2" :rules="{ required: formState.supplier?.length ? false : true, message: '请选择项目本部人员' }" extra="分包单位授权委托人和项目本部负责人必须二选一。如需选择分包单位授权委托人，必须先清空项目本部人员！">-->
				<!--						<a-select v-model:value="formState.receiver2" :disabled="formState.supplier?.length" :show-search="true" placeholder="请选择" :options="projectUserList" option-filter-prop="label" :allow-clear="true"></a-select>-->
				<!--					</a-form-item>-->
				<!--				</a-col>-->

				<a-col :span="24">
					<h4>物资清单</h4>
					<div class="table-toolbar mb-3">
						<a-space>
							<a-button type="primary" @click="addMaterialModel">
								<plus-outlined />新增
							</a-button>
						</a-space>
					</div>

					<a-table :data-source="formState.materials" :scroll="tableScroll" :pagination="false" :columns="planMaterialColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择材料名称' }">
									<a-tree-select v-model:value="formState.materials[record.key].source_id" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择材料名称" allow-clear tree-default-expand-all :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id) => changeMaterial(id, record)">
										<template #title="{ label }">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'id']" :rules="{ required: true, message: '请选择规格' }">
									<a-select v-model:value="formState.materials[record.key].id" placeholder="请选择" :options="materialOptions[record.source_id]?.models || []" allow-clear :field-names="{ value: 'value', label: 'label' }" style="width:100%" @change="(v) => changeMaterialModel(record.key, materialOptions[record.source_id]?.models, v)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', index, 'unit']" :rules="{ required: false, message: '请选择计量单位' }">
									<!--
									<a-select v-model:value="formState.materials[record.key].unit" placeholder="请选择" :options="unitOptions" :field-names="{ value: 'name' }" style="width:100%"></a-select>
									-->
									{{ formState.materials[record.key].unit || '-' }}
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'memo']">
									<a-input v-model:value="formState.materials[index].quantity" placeholder="请输入库存数量" disabled />
									<!-- {{ record }} -->
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'send_qty'">
								<a-form-item :name="['materials', index, 'send_qty']" :rules="{ required: true, message: '请输入发料数量' }">
									<a-input v-model:value="formState.materials[index].send_qty" placeholder="请输入发料数量" :rules="{ required: true, message: '请输入发料数量' }" @blur="checkQty(record)" />
								</a-form-item>
							</template>

							<template v-else-if="column.dataIndex === 'position'">
								<a-form-item :name="['materials', index, 'position']" :rules="{ required: true, message: '请输入使用部位' }">
									<!--
									<a-select v-model:value="formState.materials[record.key].position_id" placeholder="请选择" :options="projectNoOptions || []" allow-clear :field-names="{ value: 'id', label: 'name' }" style="width:100%"></a-select>
									-->
									<a-input v-model:value="formState.materials[record.key].position" placeholder="请输入使用部位" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'account_type_id'">
								<a-form-item :name="['materials', index, 'account_type_id']" :rules="{ required: true, message: '请选择核算分类' }">
									<a-select v-model:value="formState.materials[record.key].account_type_id" placeholder="请选择" :options="accountTypeOptions || []" allow-clear :field-names="{ value: 'id', label: 'name' }" style="width:100%"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'expenditure_id'">
								<a-form-item :name="['materials', index, 'expenditure_id']" :rules="{ required: true, message: '请选择支出方向' }">
									<a-select v-model:value="formState.materials[record.key].expenditure_id" placeholder="请选择" :options="expenditureOptions || []" allow-clear :field-names="{ value: 'id', label: 'name' }" style="width:100%"></a-select>
								</a-form-item>
							</template>

							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', index, 'memo']">
									<a-input v-model:value="formState.materials[index].memo" placeholder="请输入备注" />
								</a-form-item>
							</template>
							<template v-else-if="column.key === 'operation'">
								<a-space>
									<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(record.key)">
										<a-button type="link" style="color:#ff7875">
											<delete-outlined />删除
										</a-button>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
					</a-table>
				</a-col>
				<a-col :span="24">
					<a-form-item label="备注" name="memo">
						<a-textarea v-model:value="formState.memo" :auto-size="{ minRows: 4, maxRows: 6 }"></a-textarea>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-button class="cache-btn" @click="handleCache">
							<DeliveredProcedureOutlined />暂存
						</a-button>

						<a-button type="primary" html-type="submit">
							<save-outlined />提交
						</a-button>

						<a-button @click="closeTab('/uselog')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { DeleteOutlined, SaveOutlined, CloseOutlined, PlusOutlined, DeliveredProcedureOutlined } from "@ant-design/icons-vue";

import dayjs from "dayjs";
import { post, listToTree, treeToList } from "../utils";
import { useRoute } from "vue-router";
const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});
const formState = ref({ materials: [] });

const gonghaolist = ref([]); //工号列表
const gonghaoTree = ref([]);
const formRef = ref();
const supplierList = ref([]); //供应商

const projectUserList = ref([]);

const { proxy } = getCurrentInstance();
const addMaterialModel = () => {
	formState.value.materials.push({ key: formState.value.materials.length });
};

const changeSupplier = value => {
	formState.value.supplier_id = value?.[0] || "0";
	formState.value.receiver_id = value?.[1] || "";
};

const changeOprType = () => {
	formState.value.receiver_id = "";
	formState.value.supplier_id = "0";
	formState.value.supplier = [];
}

const planMaterialColumns = [
	{
		title: "ID",
		dataIndex: "key",
		width: 80,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text + 1;
		}
	},
	{
		title: "物资名称",
		dataIndex: "name",
		width: 200,
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		width: 200,
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		width: 80,
		align: "center"
	},
	{
		title: "库存数量",
		dataIndex: "quantity",
		width: 100,
		align: "center"
	},
	{
		title: "发料数量",
		dataIndex: "send_qty",
		width: 120,
		align: "center"
	},
	{
		title: "使用部位",
		dataIndex: "position",
		width: 160,
		align: "center"
	},
	{
		title: "核算分类",
		dataIndex: "account_type_id",
		width: 160,
		align: "center"
	},
	{
		title: "支出方向",
		dataIndex: "expenditure_id",
		width: 160,
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		width: 200,
		align: "center"
	},
	{},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 100,
		align: "center"
	}
];

const accountTypeOptions = ref([]);

const expenditureOptions = ref([]);

const projectOptions = ref([]);

const getSupplier = async () => {
	if (!formState.value.project_id) {
		supplierList.value = [];
		formState.value.receiver_id = '';
		return;
	}
	const result = await post("user", { is_consignor: 1, page_size: Infinity, department_id: formState.value.project_id, status: '1' });
	const supplierMap = {};
	for (const consignor of result.data) {
		const supplier = consignor.parent_user;
		const consignorOpt = consignor.departments[0]?.UserDepartment || {};
		const _day = dayjs().format('YYYY-MM-DD');
		const disabled = !consignorOpt.is_permanent && (_day > consignorOpt.end_validity || _day < consignorOpt.start_validity);
		if (!supplierMap[supplier.id]) {
			supplierMap[supplier.id] = {
				value: supplier.id,
				label: supplier.company_name,
				children: [
					{
						value: consignor.id,
						label: consignor.fullname,
						disabled
					}
				]
			};
		} else {
			supplierMap[supplier.id].children.push({
				value: consignor.id,
				label: consignor.fullname,
				disabled
			})
		}
	}
	supplierList.value = Object.values(supplierMap);
}


onMounted(async () => {
	await post("project", { is_issuance: 1 }).then(data => {
		projectOptions.value = data.map(d => {
			return {
				...d,
				value: d.id,
				label: d.name
			};
		});
	});
	await post("dictionary", { root_code: "ACCOUNT_TYPE" }).then(data => {
		accountTypeOptions.value = data;
	});

	await post("dictionary", { root_code: "EXPENDITURE" }).then(data => {
		expenditureOptions.value = data;
	});

	const cacheData = JSON.parse(localStorage.getItem("userlog-save") || '{"materials": []}');

	if (id.value) {
		formState.value = await post("uselog/info", { id: id.value }).then(data => {
			/*
			data.materials = data.materials.map((d, i) => {
				d.key = i;
				const { unit, model, quantity, send_qty, memo } = d.UselogMaterial;
				d.unit = unit;
				d.model = model;
				d.send_qty = send_qty;
				d.quantity = quantity;
				d.memo = memo;
				return d;
			});
			*/

			data.materials = data.materials.map((d, i) => ({
				key: i,
				...d.UselogMaterial,
				source_id: d.source_id,
				id: d.id
			}));

			if (data.opr_type === 1) {
				data.supplier = [data.supplier_id, data.receiver_id];
			}
			return data;
		});

		if (cacheData.id === id.value) formState.value = cacheData;
	} else {
		formState.value = cacheData;
	}

	const { project_id, gonghao_id } = formState.value;

	if (project_id) {
		changeProject(project_id);
	}

	if (gonghao_id) {
		changeProjectNo(gonghao_id);
	}
});

//const info = ref({});

//const hasPoint = ref(true);

const changeProject = async value => {
	const project_id = value;
	const { children } = projectOptions.value.find(d => d.id === project_id);
	formState.value.gonghao_id = null;
	if (!children.length) {
		return proxy.$message.error("只能选择有工号的项目");
	} else {
		// gonghaolist.value = children.map(d => ({
		// 	...d,
		// 	value: d.id,
		// 	label: d.name
		// }));
		post("department/getTrees", { type: 4, parent_id: project_id }).then(data => {
			gonghaoTree.value = data;
		});
	}
	await getSupplier();

	//获取当前项目下的所有项目本部用户
	await post("project/user", { project_id, scene: "discharge", status: '1' }).then(data => {
		projectUserList.value = data.map(d => ({
			label: d.fullname || d.username,
			value: d.id
		}));
	});

	materialOptions.value = await post("project/material", { is_issuance: 1, project_id }).then(data =>
		data.reduce((res, val) => {
			const { source_id, id, name, model, unit, stock } = val;

			if (!res[source_id])
				res[source_id] = {
					value: source_id,
					label: name,

					models: []
				};

			res[source_id].models.push({
				value: id,
				label: model,
				unit,
				stock
			});

			return res;
		}, [])
	);

	//info.value.project_id = project_id;

	/*
	await post("department/info", { id: project_id }).then(async data => {
		//获取工号data.pointData
		//pointData.value = data.pointData;
		if (data.pointData.length === 0) {
			//hasPoint.value = false;
			proxy.$message.error("只能选择有工号的项目");
		} else {
			gonghaolist.value = data.pointData.map(d => {
				return {
					value: d.id,
					label: d.name
				};
			});

			formState.value = {
				...formState.value,
				gonghao_id: null,
				materials: []
			};
		}
	});

	//获取当前项目下面的项目本部人员
	projectUserList.value = await post("user", { department_id: project_id, page_size: 10000 }).then(({ data }) =>
		data.map(d => ({
			label: d.fullname || d.username,
			value: d.id
		}))
	);
	*/

	/*
	await post("uselog/getMaterial", { project_id }).then(data => {
		//获取对应工号，对应项目的物资列表
		data = data.map((d, i) => {
			d.key = i;
			return d;
		});

		formState.value.materials = data;
	});
	*/
};

const projectNoOptions = ref([]);

//获取当前工号下的所有物料
const changeProjectNo = async (no, reset) => {
	//获取当前工号下的所有子工号
	const data = await post("project/nos", { project_no: no });
	projectNoOptions.value = listToTree(data, no);

	//清除所有物料使用部位数据
	if (reset) {
		formState.value.materials.map(d => {
			d.position_id = "";

			return d;
		});
	}
};

const checkQty = record => {
	record.send_qty = parseFloat(record.send_qty || 0);
	record.quantity = parseFloat(record.quantity || 0);

	//console.log(record.send_qty, record.quantity);
	if (record.send_qty < 0) {
		proxy.$message.error("发料数量不能小于0");
		record.send_qty = 0;
		return;
	}
	if (record.send_qty > record.quantity) {
		proxy.$message.error("发料数量不能超出了库存数量");
		record.send_qty = record.quantity;
		return;
	}
};

const saveUselog = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };

			if (!params.materials.length) {
				proxy.$message.error("请添加材料清单");
				return;
			}

			if (!params.receiver_id && !params.receiver_id) {
				proxy.$message.error("请选择委托人或内部人员");
				return;
			}


			//判断发货数量是否有超出库存
			if (params.materials.filter(d => parseFloat(d.send_qty) <= 0).length) {
				proxy.$message.error("请输入发料数量");
				return;
			}

			params.materials = JSON.stringify(params.materials);
			if (!params.receive_status) {
				params.receive_status = 1;
			}
			if (params.gonghao_id) {
				params.gonghao_id = params.gonghao_id.split('-').slice(-1)[0];
			}
			post("uselog/save", params)
				.then(() => {
					if (id.value) {
						proxy.$message.success("修改成功", 1);
					} else {
						proxy.$message.success("操作成功", 1);
					}

					localStorage.removeItem("userlog-save");
					closeTab("/Uselog");
				})
				.catch(err => {
					proxy.$message.error(err);
				});

			return;

			let has_error = 0;
			params.materials = JSON.stringify(
				params.materials.map(({ id, unit, quantity, model, send_qty, memo }) => {
					send_qty = parseFloat(send_qty);
					if (send_qty <= 0) {
						has_error = 1;
						return;
					}
					return {
						id,
						unit,
						quantity,
						send_qty,
						model,
						memo
					};
				})
			);
			if (has_error > 0) {
				proxy.$message.error("请输入发料数量");
				return;
			}
			post("uselog/save", params)
				.then(() => {
					if (id.value) {
						proxy.$message.success("修改成功", 1);
					} else {
						proxy.$message.success("操作成功", 1);
					}

					closeTab("/Uselog");
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};

/*
post("dictionary", { root_code: "MATERIAL_UNIT" }).then(data => {
	unitOptions.value = data;
});
*/

const materialOptions = ref([]);

/*
post("dictionary", { root_code: "MATERIAL_CATEGORY" }).then(data => {
	const { root_id: rootId } = data[0] || {};
	materialOptions.value = listToTree(data, rootId);

	//获取所有规格
	post("material", { source_id: data.map(d => d.id).join(","), page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value = (() => {
			const array = [];
			data.forEach(d => {
				if (!array[d.source_id]) array[d.source_id] = [];

				if (d.attr) d.model = `${d.model}（${d.attr}）`;

				array[d.source_id].push(d);
			});

			return array;
		})(data);
	});
});
*/

/*
const materialModelOptions = ref([]);
const changeMaterial = (id, record) => {
	if (!id) return;

	//强制选择规格
	record.id = null;
	record.unit = null;

	const { project_id } = formState.value;
	post("material", { source_id: id, project_id, page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value[id] = data.map(d => {
			if (d.attr) d.model = `${d.model}（${d.attr}）`;

			return d;
		});
	});
};
*/
const changeMaterial = (id, record) => {
	if (!id) return;

	//强制选择规格
	record.id = null;
	record.unit = null;

	//materialModelOptions.value = materialOptions.value[id].models || [];
};

const changeMaterialModel = (key, options, v) => {
	const { unit = "", stock = 0 } = options.find(d => d.value === v);

	const material = formState.value.materials.find(d => d.key === key);

	//判断是否已选择
	if (formState.value.materials.map(d => d.id).filter(d => d === v).length > 1) {
		proxy.$message.error("物资清单中请勿选择相同的物资规格");
		material.id = "";

		return;
	}

	material.unit = unit;
	material.quantity = stock;
};

const deleteMaterialModel = key => {
	const { materials } = formState.value;

	const index = materials.findIndex(d => d.key === key);
	if (index === false) return;
	materials.splice(index, 1);

	formState.value = {
		...formState.value,
		materials: materials.map((d, i) => {
			d.key = i;
			return d;
		})
	};
};

//调用父页面closeTab方法
/*
//父页面定义closeTab方法
provide("closeTab", path => {
	
});
*/
const closeTab = inject("closeTab");

//缓存数据
const handleCache = () => {
	localStorage.setItem("userlog-save", JSON.stringify(formState.value));
	proxy.$message.success("缓存成功");
};

const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 650
}));

const supplierFilter = (inputValue, path) => {
	return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
};
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}

	h3 {
		line-height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-bottom: 20px;

		display: flex;
		align-items: center;

		&:before {
			content: "";
			display: block;
			width: 2px;
			height: 20px;
			background: rgb(24, 144, 255);
			margin-right: 10px;
		}
	}

	h4 {
		font-weight: 600;
		margin: 15px 0;
		line-height: 30px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}

:deep(.ant-form-item-has-error) {
	padding-bottom: 20px;
}
</style>
